package com.yy.wga.mp.common.interceptor;

import com.yy.wga.common.core.dto.BaseRequestDTO;
import com.yy.wga.common.util.common.EnvUtils;
import com.yy.wga.common.web.intereceptor.RequestHolder;
import com.yy.wga.mp.common.dto.UserCacheDTO;
import com.yy.wga.mp.module.user.enums.EUserGrade;

import java.util.Objects;

/**
 * @Author: gc
 * @Date: 2024/10/22
 * @Description:
 **/
public class RequestUserHolder {

    /**
     * 用户信息
     */
    private final static ThreadLocal<UserCacheDTO> USER_INFO_THREADLOCAL = new ThreadLocal<>();
    /**
     * 公共信息
     */
    private final static ThreadLocal<BaseRequestDTO> BASE_REQUEST_THREADLOCAL = new ThreadLocal<>();

    public static UserCacheDTO getUserCache() {
        return USER_INFO_THREADLOCAL.get();
    }

    public static void setUserCache(UserCacheDTO userCacheDTO) {
        USER_INFO_THREADLOCAL.set(userCacheDTO);
    }

    public static void removeUserCache() {
        USER_INFO_THREADLOCAL.remove();
    }

    public static String getAppKey() {
        BaseRequestDTO baseRequest = RequestHolder.getBaseRequest();
        if (Objects.isNull(baseRequest)) {
            return EnvUtils.get("mp.default.appKey");
        } else {
            return baseRequest.getAppKey();
        }
    }

    public static EUserGrade getUserGrade() {
        UserCacheDTO userCache = RequestUserHolder.getUserCache();
        EUserGrade userGrade = EUserGrade.getByType(userCache.getGrade(), userCache.getLevel());
        if (Objects.isNull(userGrade)){
            return EUserGrade.COMMON;
        }
        return userGrade;
    }

    public static String getOpenId() {
        UserCacheDTO userCache = RequestUserHolder.getUserCache();
        EUserGrade userGrade = getUserGrade();
        String openId = null;
        if (Objects.isNull(userGrade) || Objects.equals(userGrade, EUserGrade.COMMON)) {
            openId = EnvUtils.get("goods.share.default.openId");
        } else {
            openId = userCache.getOpenId();
        }
        return openId;
    }
}
